package br.com.banco.control;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.banco.Logon;
import br.com.banco.entity.Conta;

/**
 * Servlet implementation class AutenticaConta
 */
public class AutenticaConta extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * Default constructor.
     */
    public AutenticaConta() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        boolean exists = false;
        Conta conta = new Conta();

        try {

            conta.setNumero(Integer.parseInt(request.getParameter("conta")));
            conta.setAgencia(Integer.parseInt(request.getParameter("agencia")));

            exists = new Logon().autenticaConta(conta);

        } catch (NumberFormatException e) {

            request.setAttribute("erros", "Conta inválida. Por favor insira somente números.");
            request.getRequestDispatcher("index.jsp").forward(request,
                    response);

        }

        if (exists) {

            request.getSession().setAttribute("conta", conta);
            request.getRequestDispatcher("fraseSecreta.jsp").forward(request,
                    response);

        } else {

            request.setAttribute("erros", "Conta não encontrada. Por favor tente novamente.");
            request.getRequestDispatcher("index.jsp").forward(request,
                    response);

        }

    }
}
